package com.mc.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.mc.jpa.MultipleChoiceRepository;
import com.mc.jpa.UsersRepository;
import com.mc.model.login.FakeLoginDto;
import com.mc.model.login.LoginDto;
import com.mc.model.login.MultipleChoice;
import com.mc.utils.CodeUtils;
import com.mc.utils.ExamUtils;
import com.xkcoding.magic.core.tool.api.R;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/*
* 美创考试controller
* */
@RequestMapping("/test")
@RestController
public class McTestController {



    @Autowired
    private UsersRepository u;
    @Autowired
    private MultipleChoiceRepository m;

    List<String> testNames = new ArrayList<>();


    /*
    * 加载登陆的人的名字
    * */
    @PostConstruct
    public void loadName(){
        testNames = FileUtil.readUtf8Lines("/Users/happysmile/Documents/code/mc-auto-test/file/testName.txt");
    }



    //假的登陆，先不登陆
    private List<HttpRequest> fakeLogin(){
        String loginUrl = "http://work.okpss.cn:58080/common/login.do";
        List<HttpRequest> requests =  new ArrayList<>();
        int i = 0;
        for (String testName : testNames) {
            if (i==1) break;
            LoginDto code = CodeUtils.getCode();
            final HttpRequest posts = HttpUtil.createPost(loginUrl)
                    .header("Cookie",code.getSessionId())
                    .body(JSONUtil.parse(FakeLoginDto.builder()
                            .username(testName)
                            .userpass("hzmcxy")
                            .usercode(code.getVCode())
                            .usertype("0")
                            .build()));
            requests.add(posts);
            i++;
        }
        return requests;
    }



    public R<String> getLoginHtml(){

        return R.success();
    }

    private String getIndexHtml(String sessionId){
        return HttpUtil.createGet("http://work.okpss.cn:58080/common/welcome.thtml")
        .header("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63")
        .header("Cookie",sessionId).execute().body();
    }


    public String parseIndexHtmlGetHistoryPage(String html) {
        Document doc = Jsoup.parse(html);
        Element table = doc.select(".tm_table_list").get(1);
        Element tbody = table.getElementsByTag("tbody").get(0);
        Element tr1 = tbody.getElementsByTag("tr").get(0);
        Element a = tr1.select("a").get(0);
        String href = a.attr("href");
        return "http://work.okpss.cn:58080/" + href;
    }

    private String getHistroyHtml(String userName){
        LoginDto code = CodeUtils.getCode();
        String vCode = Arrays.stream(code.getVCode().split("\n")).filter(e->!e.equals("\n")).collect(Collectors.joining());
        String loginUrl = "http://work.okpss.cn:58080/common/login.do";
        HttpRequest posts = HttpUtil.createPost(loginUrl)
                .header("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63")
                .header("Cookie",code.getSessionId())
                .form("username",userName)
                .form("userpass","hzmcxy")
                .form("usercode",vCode)
                .form("usertype","0");
        HttpResponse response = posts.execute();
        if (response.body().contains("登录成功")){
            System.out.println("用户：" + userName + "登陆成功");
            McTestController c = new McTestController();
            String indexHtml = c.getIndexHtml(code.getSessionId());
            if (indexHtml.contains("没有考试记录"))
                return null;
            String historyPageURL = c.parseIndexHtmlGetHistoryPage(indexHtml);
            String historyPage = HttpUtil.createGet(historyPageURL)
                    .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63")
                    .header("Cookie", code.getSessionId())
                    .execute().body();
            return historyPage;
        }else {
            System.out.println("用户：" + userName + "登陆失败");
            loginFailNames.add(userName);
            return null;
        }
    }



    public List<String> loginFailNames = new ArrayList<>();
    public List<String> failNames = new ArrayList<>();
    public List<String> secondfailNames = new ArrayList<>();

    //题目类型不允许重复
    private Map<String,MultipleChoice> titles = new HashMap<>();

    //解析然后存储
    private void doParseAndSave(String html){
        List<MultipleChoice> parse = ExamUtils.parse(html);
        for (MultipleChoice m : parse) {
            titles.put(m.getTitle(),m);
        }
    }


    public void doTest(){
        List<String> names = FileUtil.readUtf8Lines("/Users/happysmile/Documents/code/mc-auto-test/file/testName.txt");
        //List<String> names = Arrays.asList("郭子震");
        for (String name : names) {
            String histroyHtml = getHistroyHtml(name);
            if (histroyHtml == null){
                //可能是验证码识别失败，再识别几次
                failNames.add(name);
            }else {
                doParseAndSave(histroyHtml);
            }
        }
        for (String name : failNames) {
            String histroyHtml = getHistroyHtml(name);
            if (histroyHtml == null){
                //可能是验证码识别失败，再识别几次
                secondfailNames.add(name);
            }else {
                doParseAndSave(histroyHtml);
            }
        }
        ArrayList data = new ArrayList();
        for (MultipleChoice value : titles.values()) {
            data.add(value);
        }
        m.saveAll(data);
        System.out.println("登陆失败：" + loginFailNames);
        System.out.println("第一次登陆失败" + failNames);
        System.out.println("第二次登陆失败" + secondfailNames);
    }

    public void doStart(){
        doTest();
    }

    @GetMapping("/hello")
    public String hello(){
        doStart();
        return "成功";
    }

    private List<MultipleChoice> handleThese(List<MultipleChoice> ms){
        for (MultipleChoice c : ms) {
            Boolean multipleChoice = c.getMultipleChoice();
            if (multipleChoice){
                //多选
                List<String> options = c.getOptions();
                List<Integer> choices = Arrays.stream(c.getAnswer().split("&")).map(Integer::valueOf).collect(Collectors.toList());
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < options.size(); i++) {
                    if (choices.contains(i)){
                        sb.append(c.getOptions().get(i)).append("    <>    ");
                    }
                }
                c.setAnswer(sb.toString());
            }else {
                //单选
                c.setAnswer(c.getOptions().get(Integer.valueOf(c.getAnswer())));
            }
        }
        return ms;
    }

    @GetMapping("/list")
    public R list(@RequestParam("titleName") String search){
        if (StrUtil.isNotEmpty(search)){
            search = search.toLowerCase();
            List<MultipleChoice> ms = m.findByTitleLike("%" + search+ "%");
            return R.success(handleThese(ms));
        }
        return R.success(handleThese(m.findAll()));
    }




}

